package com.fattyCorps.game.service;

import com.fattyCorps.game.util.container.AutoPopQueue;
import com.fattyCorps.game.cache.PlayerCache;
import com.fattyCorps.game.obj.cache.ChatInfo;
import com.fattyCorps.game.obj.cache.PlayerInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class ChatService {

    @Autowired
    PlayerCache playerCache;

    private final int CHAT_QUEUE_MAX_SIZE = 50;

    private AtomicInteger chatId = new AtomicInteger(1);
    private AutoPopQueue<ChatInfo> chatQueue = new AutoPopQueue<>(CHAT_QUEUE_MAX_SIZE);

    public List<ChatInfo> getChatList(Integer chatId) {
        List<ChatInfo> list = chatQueue.list();
        List<ChatInfo> retList = new ArrayList<>();
        // 比较chatId和聊天消息队列中的id，找出所有大于该chatId的聊天记录
        for (int i = list.size() - 1; i >= 0; i--) {
            if (list.get(i).getId() <= chatId) {
                break;
            }

            retList.add(list.get(i));
        }

        return retList;
    }

    public void chat(Integer playerId, String content) {
        ChatInfo ci = new ChatInfo();
        int newId = chatId.getAndIncrement();
        ci.setId(newId);
        ci.setPlayerId(playerId);
        ci.setContent(content);

        PlayerInfo playerInfo = playerCache.getPlayerInfo(playerId);
        ci.setLv(playerInfo.getPlayerData().getLv());
        ci.setHead(playerInfo.getPlayerData().getHead());
        ci.setTime((int) (System.currentTimeMillis() / 1000));
        ci.setNickname(playerInfo.getNickname());

        chatQueue.push(ci);
    }
}
